package kk.json.parser;

import java.lang.reflect.Field;

import kk.json.utils.ClassUtil;
import kk.json.utils.FieldUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class BaseJSONParser<T> implements JSONParser<T> {

	@Override
	public T parse(JSONObject json, Class<T> clazz) {
		T entity = null;

		try {
			entity = clazz.newInstance();

			Field[] fields = ClassUtil.getDeclaredFields(clazz);

			for (Field field : fields) {
				String name = field.getName();
				String value = json.optString(name);

				if (value != null)
					FieldUtil.setValue(entity, name, value);
			}

		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		return entity;
	}

	@Override
	public JSONObject parse(T obj) {

		JSONObject json = new JSONObject();

		Field[] fields = ClassUtil.getDeclaredFields(obj.getClass());

		for (Field field : fields) {
			String name = field.getName();
			Object value = FieldUtil.getValue(obj, name);

			try {
				json.put(name, value);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		return json;
	}

}
